<template>
    <l-layout class="l-tab-page" v-if="!lr_loadPage" :left="240">
        <template #left>
            <l-panel :title="$t('公司信息')" style="padding-right:0;" >
                <el-tree class="learun-tree" ref="mytree" v-loading="treeLoading"  node-key="value" :data="lr_companyTree" default-expand-all :expand-on-click-node="false"  @node-click="handleNodeClick">
                    <span class="lr-tree-node"  slot-scope="{ node }">
                        <i class="learun-icon-co"></i>
                        {{ $t(node.label) }}
                    </span>
                </el-tree>
            </l-panel>
        </template>
        <l-panel style="padding-left:0;" >
            <template #toolLeft >
                 <div class="l-panel--item" >
                    <l-tree-select
                        v-model="departmentId"
                        :placeholder="$t('请选择部门')"
                        :options="lr_departmentTree(lr_departments[companyId] || [])"
                        size="mini"
                        >
                    </l-tree-select>
                </div>
                <div class="l-panel--item" >
                    <el-input :placeholder="$t('请输入关键字')"  @keyup.enter.native="hanleSearch" v-model="searchWord" size="mini" >
                        <el-button @click="hanleSearch" slot="append" icon="el-icon-search"></el-button>
                    </el-input>
                </div>
            </template>
            <template #toolRight >
                <l-tool-btns @click="handleAdd()" >
                    <l-excel-btns></l-excel-btns>
                </l-tool-btns>
            </template>
            <l-table 
                :columns="lr_getPageColumns(columns)" 
                :dataSource="tableShowData"
                :loading="loading" 
                
                isTree
                rowKey="f_PostId"
                pidKey="f_ParentId"
                defaultExpandAll
                >
                <template v-slot:f_DepartmentId="scope" >
                    {{lr_departmentName(lr_departments[companyId] || [],scope.row.f_DepartmentId)}}
                </template>
                <template v-slot:f_CreateDate="scope" >
                    {{lr_dateFormat(scope.row.f_CreateDate,'yyyy-MM-dd')}}
                </template>
                <l-table-btns :btns="tableBtns" @click="lr_handleTableBtnClick" ></l-table-btns>
            </l-table>
        </l-panel>

        <l-dialog 
            :title="formTitle"
            :visible.sync="formVisible"
            @ok="handleSave"
            @close="handleCloseForm"
            @opened="handleOpenedForm"
            >
            <my-form ref="form" ></my-form>       
        </l-dialog>

        <!--成员添加-->
        <l-fullscreen-dialog
            :title="`${$t('成员添加')}-${authName}`"
            :visible.sync="userRelationVisible"

            @ok="handleSaveUserRelation"
            @opened="handleOpenedUserRelation"
            @closed="handleClosedUserRelation"
        >
            <user-relation ref="userRelation" ></user-relation>
        </l-fullscreen-dialog>
    </l-layout>
</template>

<script>
const api = window.$api.organization.post
import MyForm from './form'
import userRelation from '../userRelation'
export default {
    components: {
        MyForm,
        userRelation
    },
    data () {
        return {
            lr_isPage:true,
            //查询
            searchWord:'',
            searchTableData:null,

            loading:false,
            tableData:[],
            columns: [
                {label:'名称',prop:'f_Name',minWidth:'160'},
                {label:'编号',prop:'f_EnCode',width:'110'},
                {label:'部门',prop:'f_DepartmentId',width:'120'},
                {label:'创建人',prop:'f_CreateUserName',width:'100'},
                {label:'创建时间',prop:'f_CreateDate',width:'100'}
            ],
            tableBtns:[
                {prop:'Edit',label:this.$t('编辑'),width:40},
                {prop:'Delete',label:this.$t('删除'),width:40},
                {prop:'MemberAdd',label:this.$t('添加成员'),width:60}
            ],
            companyId:'',
            treeLoading:false,
            departmentId:'',
            departmentLoading:false,


            formVisible:false,
            formTitle:'',
            formEditRow:null,
            formEdit:false,

            userRelationVisible:false,
            authName:''
        };
    },
    computed:{
        list(){
            return this.lr_posts[this.companyId] || []
        },
        tableShowData(){
            let list = this.list

            if(this.searchTableData){
                list = this.searchTableData
            }

            if(this.departmentId){
                list = list.filter(t=>t.f_DepartmentId == this.departmentId)
            }

            return list
        }
    },
    mounted () {
        this.init()
    },
    methods:{
        async init(){
            this.companyId = '53298b7a-404c-4337-aa7f-80b2a4ca6681'
            this.loadTableData()
            this.lr_loadDepartments(this.companyId)

            this.treeLoading = true
            await this.lr_loadCompanys()
            if(this.lr_companyTree.length >0){
                this.companyId = this.lr_companyTree[0].f_CompanyId
                if (this.$refs["mytree"]) this.$refs["mytree"].setCurrentKey(this.companyId )
                this.loadTableData()
            }
            
            this.treeLoading = false
        },

        async loadTableData(){
            this.loading = true
            await this.lr_loadPosts(this.companyId,false)
            this.loading = false
        },
        handleNodeClick(data) {
            this.companyId = data.f_CompanyId
            this.departmentId = ''
            this.lr_loadDepartments(this.companyId)
            this.loadTableData()
        },
        hanleSearch(){
            if(this.searchWord){
                this.searchTableData = this.list.filter(item => item.f_Name.indexOf(this.searchWord) >-1 || item.f_EnCode.indexOf(this.searchWord)>-1)
            }
            else{
                this.searchTableData = null
            }
        }, 
        handleAdd(){
            if(this.companyId){
                this.formEdit = false
                this.showForm('新增岗位')
            }
            else{
                this.$message({
                    type: 'warning',
                    message: this.$t('请选择左侧公司!')
                })
            }
        },
        handleEdit($index,row){
            this.formEdit = true
            this.formEditRow = row
            this.showForm('编辑岗位')
            
        },
        handleDelete($index,row){
            this.$confirm(this.$t('此操作将永久删除该数据, 是否继续?'), this.$t('提示'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
            }).then(() => {
                api.remove(row.f_PostId).then(()=> {
                    this.$message({
                        type: 'success',
                        message: this.$t('删除成功!')
                    });
                    this.loadTableData();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: this.$t('已取消删除')
                })      
            })
        },
        handleSave(showLoading,hideLoading){
            this.$refs.form.validateForm(()=>{
                showLoading()
                const formData = this.$refs.form.getForm()
                if(this.formEdit){// 修改数据
                    api.update(formData.f_PostId,formData).then(()=> {
                        hideLoading()
                        this.formVisible = false
                        this.$message({
                            type: 'success',
                            message: this.$t('更新成功!')
                        })
                        this.loadTableData()
                    }).catch(() => {
                        hideLoading()
                    })
                }
                else{// 新增数据
                    api.add(formData).then(()=> {
                        hideLoading()
                        this.formVisible = false;
                        this.$message({
                            type: 'success',
                            message: this.$t('添加成功!')
                        })
                        this.loadTableData()
                    }).catch(() => {
                        hideLoading()
                    })
                }
            });
        },
        handleOpenedForm(){
            if(this.formEdit){
                this.$refs.form.setForm(this.formEditRow)
            }
            else{
                const formData = this.$refs.form.getForm()
                formData.f_CompanyId = this.companyId
                this.$refs.form.setForm(formData)
            }
        },
        handleCloseForm(){
            this.$refs.form.resetForm()
        },
        showForm(text){
            this.formTitle = text
            this.formVisible = true
        },

        /*成员添加*/
        handleMemberAdd($index,row){
            this.formEditRow = row
            this.authName = row.f_Name
            this.userRelationVisible = true
        },

        handleOpenedUserRelation(){
            this.$refs.userRelation.setForm(this.formEditRow.f_PostId,2)
        },
        handleClosedUserRelation(){
            this.$refs.userRelation.resetForm()
        },
        async handleSaveUserRelation(){
            await this.$refs.userRelation.saveForm()
            this.userRelationVisible = false
        },

    }

}
</script>
